import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class PrizeAnalysis {

    public static void main(String[] args) {
        String filePath = "prize_draw_nums.txt";
        Map<String, List<Integer>> prizeData = readPrizeData(filePath);

        if (prizeData == null) {
            System.out.println("无法读取文件数据！");
            return;
        }

        System.out.println("中奖结果分析：");
        for (Map.Entry<String, List<Integer>> entry : prizeData.entrySet()) {
            String prize = entry.getKey();
            List<Integer> drawNums = entry.getValue();

            if (drawNums.isEmpty()) {
                System.out.printf("%s：无中奖数据\n", prize);
                continue;
            }

            // 计算中奖次数
            int count = drawNums.size();

            // 计算中奖间隔
            List<Integer> intervals = new ArrayList<>();
            for (int i = 1; i < drawNums.size(); i++) {
                intervals.add(drawNums.get(i) - drawNums.get(i - 1));
            }

            // 计算均值和方差
            double mean = intervals.stream().mapToInt(Integer::intValue).average().orElse(0.0);
            double variance = intervals.stream()
                    .mapToDouble(i -> Math.pow(i - mean, 2))
                    .average()
                    .orElse(0.0);

            System.out.printf("%s：\n", prize);
            System.out.printf("  中奖次数：%d\n", count);
            System.out.printf("  中奖间隔均值：%.2f\n", mean);
            System.out.printf("  中奖间隔方差：%.2f\n", variance);
        }
    }

    private static Map<String, List<Integer>> readPrizeData(String filePath) {
        Map<String, List<Integer>> prizeData = new LinkedHashMap<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("：");
                if (parts.length < 2) continue;

                String prize = parts[0].trim();
                String[] nums = parts[1].split("，");
                List<Integer> drawNums = Arrays.stream(nums)
                        .filter(s -> s.matches("第\\d+次抽奖抽中"))
                        .map(s -> Integer.parseInt(s.replaceAll("[^\\d]", "")))
                        .collect(Collectors.toList());

                prizeData.put(prize, drawNums);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return prizeData;
    }
}